/**
 * 工作项详情模态框组件
 */

'use client';

import React from 'react';
import {
  Modal,
  Descriptions,
  Tag,
  Avatar,
  Space,
  Typography,
  Divider,
  Progress,
  Timeline,
  Empty,
} from 'antd';
import {
  UserOutlined,
  ClockCircleOutlined,
  CalendarOutlined,
  TagOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import type { WorkItem } from '../types/workItem';

const { Text, Paragraph } = Typography;

interface WorkItemDetailModalProps {
  workItem: WorkItem | null;
  visible: boolean;
  onClose: () => void;
}

export default function WorkItemDetailModal({
  workItem,
  visible,
  onClose,
}: WorkItemDetailModalProps) {
  if (!workItem) {
    return (
      <Modal
        title="工作项详情"
        open={visible}
        onCancel={onClose}
        footer={null}
        width={800}
      >
        <Empty description="没有工作项数据" />
      </Modal>
    );
  }

  const getTypeTag = (type: string) => {
    const typeMap: Record<string, { color: string; text: string }> = {
      epic: { color: 'purple', text: '史诗' },
      feature: { color: 'blue', text: '特性' },
      story: { color: 'green', text: '用户故事' },
      task: { color: 'orange', text: '任务' },
      bug: { color: 'red', text: '缺陷' },
      issue: { color: 'gray', text: '事务' },
    };
    const config = typeMap[type] || { color: 'default', text: type };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getPriorityColor = (priority?: string) => {
    const priorityMap: Record<string, string> = {
      highest: '#ff4d4f',
      high: '#ff7a45',
      medium: '#fadb14',
      low: '#52c41a',
      lowest: '#1890ff',
    };
    return priorityMap[priority || ''] || '#d9d9d9';
  };

  const renderAssignee = (assignee?: WorkItem['assignee']) => {
    if (!assignee) return <Text type="secondary">未指派</Text>;
    
    return (
      <Space>
        <Avatar 
          size="small" 
          src={assignee.avatar}
          icon={!assignee.avatar ? <UserOutlined /> : undefined}
        >
          {!assignee.avatar ? assignee.display_name?.[0] : undefined}
        </Avatar>
        <Text>{assignee.display_name}</Text>
      </Space>
    );
  };

  const renderWorkload = () => {
    const estimated = workItem.estimated_workload || 0;
    const remaining = workItem.remaining_workload || 0;
    const completed = Math.max(0, estimated - remaining);
    const percent = estimated > 0 ? Math.round((completed / estimated) * 100) : 0;

    if (estimated === 0) return <Text type="secondary">未设置</Text>;

    return (
      <Space direction="vertical" size="small" style={{ width: '100%' }}>
        <Progress
          percent={percent}
          strokeColor={percent >= 100 ? '#52c41a' : undefined}
        />
        <Text>
          已完成: {completed}h / 总计: {estimated}h / 剩余: {remaining}h
        </Text>
      </Space>
    );
  };

  const renderTimeline = () => {
    const timelineItems = [
      {
        color: 'green',
        dot: <CalendarOutlined />,
        children: (
          <div>
            <Text strong>创建时间</Text>
            <br />
            <Text type="secondary">
              {dayjs.unix(workItem.created_at).format('YYYY-MM-DD HH:mm:ss')}
            </Text>
            <br />
            <Text>创建人: {workItem.created_by.display_name}</Text>
          </div>
        ),
      },
    ];

    if (workItem.start_at) {
      timelineItems.push({
        color: 'blue',
        dot: <ClockCircleOutlined />,
        children: (
          <div>
            <Text strong>开始时间</Text>
            <br />
            <Text type="secondary">
              {dayjs.unix(workItem.start_at).format('YYYY-MM-DD HH:mm:ss')}
            </Text>
          </div>
        ),
      });
    }

    if (workItem.end_at) {
      timelineItems.push({
        color: 'orange',
        dot: <ClockCircleOutlined />,
        children: (
          <div>
            <Text strong>结束时间</Text>
            <br />
            <Text type="secondary">
              {dayjs.unix(workItem.end_at).format('YYYY-MM-DD HH:mm:ss')}
            </Text>
          </div>
        ),
      });
    }

    if (workItem.completed_at) {
      timelineItems.push({
        color: 'green',
        dot: <ClockCircleOutlined />,
        children: (
          <div>
            <Text strong>完成时间</Text>
            <br />
            <Text type="secondary">
              {dayjs.unix(workItem.completed_at).format('YYYY-MM-DD HH:mm:ss')}
            </Text>
          </div>
        ),
      });
    }

    timelineItems.push({
      color: 'gray',
      dot: <ClockCircleOutlined />,
      children: (
        <div>
          <Text strong>最后更新</Text>
          <br />
          <Text type="secondary">
            {dayjs.unix(workItem.updated_at).format('YYYY-MM-DD HH:mm:ss')}
          </Text>
          <br />
          <Text>更新人: {workItem.updated_by.display_name}</Text>
        </div>
      ),
    });

    return <Timeline items={timelineItems} />;
  };

  return (
    <Modal
      title={
        <Space>
          <Text strong>{workItem.identifier}</Text>
          <Text>{workItem.title}</Text>
        </Space>
      }
      open={visible}
      onCancel={onClose}
      footer={null}
      width={900}
      styles={{ body: { maxHeight: '70vh', overflow: 'auto' } }}
    >
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        {/* 基本信息 */}
        <Descriptions title="基本信息" column={2} size="small">
          <Descriptions.Item label="编号">
            <Tag color="blue">{workItem.identifier}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="类型">
            {getTypeTag(workItem.type)}
          </Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag color={workItem.state.color}>{workItem.state.name}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="优先级">
            {workItem.priority ? (
              <Tag color={getPriorityColor(workItem.priority.id)}>
                {workItem.priority.name}
              </Tag>
            ) : (
              <Text type="secondary">未设置</Text>
            )}
          </Descriptions.Item>
          <Descriptions.Item label="负责人">
            {renderAssignee(workItem.assignee)}
          </Descriptions.Item>
          <Descriptions.Item label="项目">
            <Space direction="vertical" size={0}>
              <Text strong>{workItem.project.name}</Text>
              <Text type="secondary">{workItem.project.identifier}</Text>
            </Space>
          </Descriptions.Item>
        </Descriptions>

        {/* 描述 */}
        {workItem.description && (
          <>
            <Divider />
            <div>
              <Text strong>描述</Text>
              <Paragraph style={{ marginTop: 8 }}>
                {workItem.description}
              </Paragraph>
            </div>
          </>
        )}

        {/* 工作量信息 */}
        <Divider />
        <Descriptions title="工作量" column={2} size="small">
          <Descriptions.Item label="故事点">
            {workItem.story_points || <Text type="secondary">未设置</Text>}
          </Descriptions.Item>
          <Descriptions.Item label="工时进度" span={2}>
            {renderWorkload()}
          </Descriptions.Item>
        </Descriptions>

        {/* 扩展信息 */}
        {(workItem.version || workItem.sprint || workItem.board) && (
          <>
            <Divider />
            <Descriptions title="关联信息" column={2} size="small">
              {workItem.version && (
                <Descriptions.Item label="版本">
                  <Text>{workItem.version.name}</Text>
                </Descriptions.Item>
              )}
              {workItem.sprint && (
                <Descriptions.Item label="迭代">
                  <Text>{workItem.sprint.name}</Text>
                </Descriptions.Item>
              )}
              {workItem.board && (
                <Descriptions.Item label="看板">
                  <Text>{workItem.board.name}</Text>
                </Descriptions.Item>
              )}
              {workItem.entry && (
                <Descriptions.Item label="看板栏">
                  <Text>{workItem.entry.name}</Text>
                </Descriptions.Item>
              )}
              {workItem.swimlane && (
                <Descriptions.Item label="泳道">
                  <Text>{workItem.swimlane.name}</Text>
                </Descriptions.Item>
              )}
              {workItem.parent && (
                <Descriptions.Item label="父工作项">
                  <Space>
                    <Tag color="blue">{workItem.parent.identifier}</Tag>
                    <Text>{workItem.parent.title}</Text>
                  </Space>
                </Descriptions.Item>
              )}
            </Descriptions>
          </>
        )}

        {/* 标签 */}
        {workItem.tags && workItem.tags.length > 0 && (
          <>
            <Divider />
            <div>
              <Text strong>
                <TagOutlined /> 标签
              </Text>
              <div style={{ marginTop: 8 }}>
                {workItem.tags.map(tag => (
                  <Tag key={tag.id}>{tag.name}</Tag>
                ))}
              </div>
            </div>
          </>
        )}

        {/* 关注人 */}
        {workItem.participants && workItem.participants.length > 0 && (
          <>
            <Divider />
            <div>
              <Text strong>
                <UserOutlined /> 关注人
              </Text>
              <div style={{ marginTop: 8 }}>
                <Space wrap>
                  {workItem.participants.map(participant => (
                    participant.user && (
                      <Space key={participant.id} size="small">
                        <Avatar 
                          size="small" 
                          src={participant.user.avatar}
                          icon={!participant.user.avatar ? <UserOutlined /> : undefined}
                        >
                          {!participant.user.avatar ? participant.user.display_name?.[0] : undefined}
                        </Avatar>
                        <Text>{participant.user.display_name}</Text>
                      </Space>
                    )
                  ))}
                </Space>
              </div>
            </div>
          </>
        )}

        {/* 时间线 */}
        <Divider />
        <div>
          <Text strong>
            <ClockCircleOutlined /> 时间线
          </Text>
          <div style={{ marginTop: 16 }}>
            {renderTimeline()}
          </div>
        </div>
      </Space>
    </Modal>
  );
}